require([ "dojo", "dojo/_base/xhr", "dojo/on", "dojo/dom", "dojo/dom-class", "dojo/parser",
  		"dojo/query", "dojo/dom-attr", "dojo/dom-style", "dojo/dom-construct", "dojo/keys",
  		"dojox/widget/Standby", "dojo/fx/Toggler", "dojo/fx", "dojo/_base/fx", "dojox/fx/text", 
  		"dojox/html", "dojox/validate", "dojo/_base/connect", 
  		"dijit/registry", "dojo/_base/array", "dojo/_base/lang", "dojo/_base/declare",  
  		"dojoCustom/profileWidget", "dojoCustom/paginationWidget", "dojo/io/iframe",
  		"dojoCustom/slideShowWidget", "dojo/hash", "dojo/topic", "dojo/text!/static/json/usstates.json",
  		"dojox/fx", 
  		"dojox/html/_base", 
  		"dijit/TooltipDialog", "dojo/NodeList-traverse", "dojo/NodeList-manipulate",
  		"dojo/io/script",
  		"dojox/validate/us", "dojox/validate/web", "dijit/form/CheckBox", "dijit/form/Textarea",
  		"dijit/form/Select", "dijit/form/TextBox", "dijit/form/ValidationTextBox", "dijit/form/DateTextBox",
  		"dijit/form/Button",
  		"dijit/form/RadioButton", "dijit/form/Form", "dijit/form/ComboBox", "dojo/store/Memory",
  		"dojo/domReady!" ],
		function(dojo, xhr, on, dom, domClass, parser, query, domAttr, domStyle, construct, keys,
			Standby, Toggler, fx, baseFx, text, html, validate, connect, registry, array, lang, declare,
			profileWidget, pagination, iframe, slideShow, hash, topic, states) {
			parser.parse();
			
			on(query(".link"), "click", function(e){
				loadContentPane(e.currentTarget);
			});
			
			destroyWidgets = function() {
				array.forEach(registry.toArray(), function(widget, i) {
					// console.log(widget.declaredClass);
					if (widget.declaredClass != 'dojox.widget.Standby' && widget.declaredClass != 'dijit._MasterTooltip') { 
						widget.destroy();
					}
				});
				// console.log(registry.length);
			}
			
			loadContentPane = function(target) {
				contenturl = domAttr.get(target, "link");
				console.log(" handling loadContentPane using " + target + " and context url "
						+ contenturl);
				if (contenturl) {
					destroyWidgets();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							console.log("error occurred .. code " + 451);
							dom.byId("content_wrapper").innerHTML = "";
						}
					});
				} else {
					console.log("error occurred .. code " + 452);
					dom.byId("content_wrapper").innerHTML = "";
				}
			}
			
			loadContentPaneCallback = function(newContent, ioargs){
				if (contenturl.indexOf("nexus2Banner.htm") != -1) {
					updateContentPane(newContent, dojo.byId("content_wrapper"));
					parser.parse("content_wrapper");
				} else if (contenturl.indexOf("n2registration.htm") != -1) {
					updateContentPane(newContent, dojo.byId("content_wrapper"));
					parser.parse("content_wrapper");
					handleUserRegistrationSubmit();
				} else if(contenturl.indexOf("n2Login.htm") != -1){
					updateContentPane(newContent, dojo.byId("content_wrapper"));
					parser.parse("content_wrapper");
					handleLoginSubmit();
				}
				else{
					updateContentPane(newContent, dojo.byId("content_wrapper"));
					parser.parse("content_wrapper");
				}
			}
			
			updateContentPane = function(newContent, container){
				html.set(container, newContent, {
			        executeScripts: true,
			        scriptHasHooks: false,
			        renderStyles: true
			    });
			}
			
			
			
			
			// http://www.sitepoint.com/html5-file-drag-and-drop/
			// http://jsfiddle.net/danielzen/utp7j/
			var fileuploadurl;
			var blobkey;
			// file drag hover
			FileDragHover = function(e) {
				e.stopPropagation();
				e.preventDefault();
				e.target.className = (e.type == "dragover" ? "hover" : "");
			}
			
			uploadProgress = function(evt) {
				/* This event is raised when the server send back a response */
		    }
			
			uploadComplete = function(evt) {
			        /* This event is raised when the server send back a response */
				 console.log(evt.target.responseText)
				 blobkey = evt.target.responseText;
				 xhr.get({
						url : "/public/n2servingImgUrl.htm?blobkey=" + blobkey,
						load : function(data){
							console.log(data);
							var responseJson = JSON.parse(data);
							profilePicDom = construct.create("img", {alt: "profile pic", src: responseJson.servingurl, style: "width: 100%"});
							fileuploadurl = responseJson.uploadurl;
							construct.place(profilePicDom, "filedrag", "only");  
							domStyle.set("filedrag", "border", "0");
						}
					});
			}
			
			ParseFile = function(file) {
				console.log(file);
				var fd = new FormData();
				fd.append("uploadedFile", file);
		        var xhr = new XMLHttpRequest();
		        xhr.upload.addEventListener("progress", uploadProgress, false);
		        xhr.addEventListener("load", uploadComplete, false);
		        xhr.open("POST", fileuploadurl);
		        xhr.send(fd);
			}
			
			// file selection
			FileSelectHandler = function(e) {
				// cancel event and hover styling
				FileDragHover(e);
				// fetch FileList object
				var files = e.target.files || e.dataTransfer.files;
				// process all File objects
				for (var i = 0, f; f = files[i]; i++) {
					ParseFile(f);
				}
			}
			
			//
			// initialize
			initFileUpload = function(uploadurl) {
				fileuploadurl = uploadurl
				var filedrag = dom.byId("filedrag");
				// is XHR2 available?
				var xhr = new XMLHttpRequest();
				if (xhr.upload) {
					// file drop
					filedrag.addEventListener("dragover", FileDragHover, false);
					filedrag.addEventListener("dragleave", FileDragHover, false);
					filedrag.addEventListener("drop", FileSelectHandler, false);
				}
			}
			
			
			handleUserRegistrationSubmit = function() {
				var regForm = dojo.byId("registerForm"); 
				dojo.connect(regForm,"onsubmit", function(e) {
					domAttr.set(query("#imageBlobKey")[0], "value", blobkey);
					var xhrArgs = {
						form : dojo.byId("registerForm"),
						url: '/public/n2registerUser.htm',
						load : function(data) {
							var regResult = JSON.parse(data);
							if(regResult.result == 'success'){
								contenturl = "/profile/n2UserProfile.htm";
								loadContentPanewithUrl(contenturl); 
							} else {
								console.log("xhrget response data: " + data);
								domStyle.set("regFormMessageDiv", "display", "inline");
								dojo.byId("regFormMessage").innerHTML = data;
							}
						},
						error : function(error) {
							dojo.byId("content_wrapper").innerHTML = "";
						}
					}
					if(registry.byId("registerForm").validate()){ 
						xhr.post(xhrArgs);		
					} else {
						console.log('validation failed');
					}
							
				});
			}
			
			loadContentPanewithUrl = function(contenturl) {
				console.log(" handling loadContentPane with context url "
						+ contenturl);
				if (contenturl) {
					destroyWidgets();
					xhr.get({
						url : contenturl,
						load : loadContentPaneCallback,
						error : function() {
							dom.byId("content_wrapper").innerHTML = "";
						}
					});
				} else {
					dom.byId("content_wrapper").innerHTML = "";
				}
			}
			
			handleLoginSubmit = function(){
				var loginForm = dojo.byId("loginForm");
				dojo.connect(loginForm,"onsubmit", function(e) {
					var xhrArgs = {
						form : dojo.byId("loginForm"),
						url: '/j_spring_security_check',
						load : function(data) {
							if (data.indexOf("loginPageResponse") != -1) {
								destroyWidgets();
								html.set(dojo.byId("contentpane"), data, {
							        executeScripts: true,
							        scriptHasHooks: false,
							        renderStyles: true
							    });								
								parser.parse("login_div_container"); 
								handleLoginSubmit();
							}else {
								contenturl = "/profile/n2UserProfile.htm";
								loadContentPanewithUrl(contenturl); 
							}
						},
						error : function(error) {
							dojo.byId("content_wrapper").innerHTML = "error occurred";
							destroyWidgets();
						}
					}
					
					if(registry.byId("loginForm").validate()){ 
						xhr.post(xhrArgs);
					} else {
						
					}
				});
			}
			
			
	});